<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Edit, Delete } from '@element-plus/icons-vue'
import { queryEntity, delEntity, createFromDB } from '@/api/develop/entity'
import { useAppStore } from '@/store/modules/app'
import { useI18n } from '@/hooks/web/useI18n'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import { Paging } from '@/config/public'
import { useEmitt } from '@/hooks/web/useEmitt'
import { useRouter } from 'vue-router'
import { selectModule, selectDataSource } from '@/api/develop'
import { ModuleTree } from '@/components/Tree'

defineOptions({
  name: 'EntityManage'
})

const appStore = useAppStore()
const { t } = useI18n()
const { push, currentRoute } = useRouter()
const localeStore = useLocaleStoreWithOut()
const curLang = localeStore.getCurrentLocale.lang
const formRef = ref()

const state = reactive({
  searchKey: '',
  // 表格數據
  tableView: [{}],
  // 分頁相關屬性
  totalCount: 0,
  pageSizes: Paging.sizes,
  queryBody: {
    key: '',
    pageNo: 1,
    pageSize: Paging.defaultSize,
    params: {
      'Q_e.status_I_LT': 4
    },
    sortField: '',
    sortOrder: ''
  },
  dialogVisible: false,
  dialogForm: { moduleId: '', dsId: '', tableName: '' },
  dialogRule: {
    moduleId: {
      required: true,
      message: t('orderNo.module') + t('common.notEmpty'),
      trigger: ['blur']
    },
    tableName: {
      required: true,
      message: t('entity.viewName') + t('common.notEmpty'),
      trigger: ['blur']
    }
  },
  dialogModName: 'moduleName',
  entNameField: 'entName',
  modNameField: 'moduleName',
  moduleList: [],
  dsList: []
})
onMounted(async () => {
  if (curLang == 'en') {
    state.entNameField = 'enName'
    state.modNameField = 'enModuleName'
    state.dialogModName = 'enName'
  } else if (curLang == 'zh_HK') {
    state.entNameField = 'hkName'
    state.modNameField = 'hkModuleName'
    state.dialogModName = 'hkName'
  }
  state.moduleList = await selectModule()
  init()
})

//从数据库反向生成实体
const createEntity = () => {
  formRef.value.validate(async (vaild) => {
    if (!vaild) {
      return
    }
    let form = Object.assign({}, state.dialogForm)
    await createFromDB(form).then((res) => {
      const result = res as any
      if (!res) {
        return
      }
      //保存成功
      if (result.success) {
        ElMessage.success(t('common.addSuccess'))
        state.dialogVisible = false
        handleSearch()
      }
    })
  })
}

//根据模块变化刷新数据源
const refreshDsList = async (event) => {
  const moduleId = event
  if (!moduleId || moduleId.length == 0) {
    return
  }
  state.dsList = (await selectDataSource(moduleId)).data
  //formRef.value.clearValidate(['dsId'])
  //校验数据源ID
  if (state.dialogForm.dsId) {
    if (!containDsId(state.dsList, state.dialogForm.dsId)) {
      state.dialogForm.dsId = ''
    }
  }
}
//检查列表中是否包含当前数据源ID
const containDsId = (dsList, dsId) => {
  if (!dsList || !dsId) {
    return false
  }
  for (let ds of dsList) {
    if (ds.dsId == dsId) {
      return true
    }
  }
  return false
}

const changePage = (page) => {
  state.queryBody.pageNo = page
  init()
}
const changePageSize = (pageSize) => {
  state.queryBody.pageSize = pageSize
  state.queryBody.pageNo = 1
  init()
}
// 刪除当前记录
const deleteOne = (row) => {
  ElMessageBox.confirm(t('entity.deleteTip1'), t('common.warning'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      await delEntity(row.entId)
      init()
    })
    .catch(() => {})
}

// 修改
const edit = (id) => {
  push({
    name: 'EntityAdd',
    query: {
      id: id,
      fromPath: currentRoute.value.fullPath,
      moduleId: state.dialogForm.moduleId
    }
  })
}

/**
 * @description  定义列表刷新事件
 * @author Elwin ZHANG
 * @date 2022-06-08 11:44
 */
useEmitt({
  //刷新列表事件
  name: 'refreshEntityList',
  callback: (type: string) => {
    if (type === 'add') {
      state.queryBody.pageNo = 1
    }
    handleSearch()
  }
})

// 搜索
const handleSearch = () => {
  state.queryBody.key = state.searchKey
  init()
}

//重置查询
const resetSearch = () => {
  state.searchKey = ''
  state.queryBody.params['Q_e.module_id_S_IN'] = ''
  handleSearch()
}
//点击模块树节点
const handleNodeClick = (data) => {
  state.queryBody.params['Q_e.module_id_S_IN'] = data
  state.dialogForm.moduleId = data.split(',')[0]
  refreshDsList(state.dialogForm.moduleId)
  handleSearch()
}

//渲染页面的接口
const init = async () => {
  appStore.setFooter(false)
  state.tableView = []
  await queryEntity(state.queryBody)
    .then((res) => {
      const result = res as any
      var data = result.result.data
      state.tableView = data
      state.totalCount = result.result.totalCount
    })
    .catch(() => {})
}
</script>
<template>
  <div>
    <!-- 搜索條件卡片 -->
    <el-card class="box-card">
      <el-row :gutter="10" style="padding: 5px 5px; line-height: 28px" align="middle">
        <el-col :sm="5" :md="4" style="text-align: right">{{ $t('common.searchKey') }}</el-col>
        <el-col :sm="19" :md="12" style="text-align: left">
          <el-input
            v-model="state.searchKey"
            @keyup.enter="handleSearch"
            :placeholder="
              $t('common.inputText') +
              $t('entity.name') +
              '/' +
              $t('entity.tableName') +
              '/' +
              $t('common.remark')
            "
          />
        </el-col>
        <el-col :sm="24" :md="8" style="text-align: right">
          <div style="margin-right: -5px">
            <el-button @click="handleSearch" type="primary" size="small" plain
              ><Icon icon="ic:outline-search" /><span>{{ $t('common.query') }}</span></el-button
            >
            <el-button @click="resetSearch" type="info" size="small" plain>
              <Icon icon="icon-park-solid:clear-format" /><span>{{
                $t('common.reset')
              }}</span></el-button
            >
            <el-button size="small" plain @click="state.dialogVisible = true">
              <Icon icon="bi:database-add" /><span>{{ $t('entity.reverse') }}</span>
            </el-button>
            <el-button type="success" size="small" plain @click="edit(null)">
              <Icon icon="material-symbols:add-circle-rounded" /><span>{{ $t('common.add') }}</span>
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-container class="mainArea">
      <el-aside width="200px">
        <ModuleTree @node-click="handleNodeClick" />
      </el-aside>
      <el-main class="formcard">
        <!-- 搜索結果表格 -->
        <el-table
          :data="state.tableView"
          tooltip-effect="light"
          style="width: 100%; border: 1px solid #ddd; font-size: 12px"
          stripe
          row-key="id"
          default-expand-all
          :header-cell-style="{
            background: 'var(--el-color-primary-light-9)',
            color: '#409eff'
          }"
        >
          <el-table-column type="index" min-width="60">
            <template #header>
              <div style="margin-bottom: -10px">
                <Icon
                  icon="ant-design:field-number-outlined"
                  size="24"
                  :title="$t('common.number')"
              /></div>
            </template>
          </el-table-column>
          <el-table-column
            :prop="state.entNameField"
            :label="$t('entity.name')"
            show-overflow-tooltip
            min-width="100"
          />
          <el-table-column prop="tableName" :label="$t('entity.tableName')" min-width="120" />
          <el-table-column
            :prop="state.modNameField"
            :label="$t('orderNo.module')"
            min-width="110"
          />
          <el-table-column
            prop="isGenDb"
            :label="$t('entity.genDb')"
            min-width="100"
            align="center"
          >
            <template #default="{ row }">
              <span v-if="row.isGenDb == 1">{{ $t('common.yes') }}</span>
              <span v-else>{{ $t('common.no') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="dsName" :label="$t('datasource.name')" min-width="100" />
          <el-table-column prop="status" :label="$t('common.status')" min-width="70" align="center">
            <template #default="{ row }">
              <span v-if="row.status == 0">{{ $t('entity.status0') }}</span>
              <span v-else>{{ $t('entity.status1') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="updateBy" :label="$t('common.updateBy')" min-width="85" />
          <el-table-column prop="updateTime" :label="$t('common.updateTime')" width="143" />
          <el-table-column fixed="right" :label="$t('common.operation')" width="100" align="center">
            <template #default="{ row }">
              <el-button
                type="primary"
                plain
                circle
                size="small"
                :title="$t('common.modify')"
                @click="edit(row.entId)"
              >
                <el-icon>
                  <Edit />
                </el-icon>
              </el-button>
              <el-button
                type="danger"
                plain
                circle
                size="small"
                :title="$t('common.delete')"
                v-if="row.isBuildIn != 1"
                @click="deleteOne(row)"
              >
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分頁器 -->
        <div class="demo-pagination-block"
          ><el-pagination
            v-model:currentPage="state.queryBody.pageNo"
            v-model:page-size="state.queryBody.pageSize"
            @current-change="changePage"
            @size-change="changePageSize"
            :page-sizes="state.pageSizes"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="state.totalCount"
        /></div>
      </el-main>
    </el-container>
  </div>
  <!-- 反向生成实体对话框 -->
  <el-dialog v-model="state.dialogVisible" :title="$t('entity.reverse')" width="800px" draggable>
    <el-form :model="state.dialogForm" :rules="state.dialogRule" label-width="auto" ref="formRef">
      <el-row>
        <el-col :sm="24" :md="12">
          <el-form-item :label="$t('orderNo.module')" prop="moduleId">
            <el-select
              v-model="state.dialogForm.moduleId"
              :placeholder="$t('common.selectText')"
              size="default"
              @change="refreshDsList($event)"
            >
              <el-option
                v-for="item in state.moduleList"
                :key="item.moduleId"
                :label="item[state.modNameField]"
                :value="item.moduleId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :sm="24" :md="12">
          <el-form-item :label="$t('entity.dataSource')" prop="dsId">
            <el-select
              v-model="state.dialogForm.dsId"
              :placeholder="$t('common.selectText')"
              size="default"
            >
              <el-option
                v-for="item in state.dsList"
                :key="item.dsId"
                :label="item.dsName"
                :value="item.dsId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :sm="24" :md="12">
          <el-form-item :label="$t('entity.viewName')" prop="tableName">
            <el-input
              v-model="state.dialogForm.tableName"
              :placeholder="$t('common.inputText') + $t('entity.tableName')"
              maxlength="50"
              show-word-limit
            /> </el-form-item></el-col
      ></el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer" style="text-align: center">
        <el-button @click="createEntity()" type="primary" plain>
          <Icon icon="material-symbols:add-circle-rounded" />
          <span> {{ $t('entity.generate') }}</span></el-button
        >
        <el-button @click="state.dialogVisible = false" plain type="info">
          <Icon icon="ri:arrow-go-back-fill" />
          <span> {{ $t('common.back') }}</span>
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<style lang="less" scoped>
:deep(.el-card__header) {
  border-bottom: 0;
  box-sizing: border-box;
}

:deep(.el-select .el-option .el-input .el-select-dropdown__item) {
  font-size: 12px;
}

:deep(.el-input__inner) {
  &::placeholder {
    font-size: 12px;
  }
  font-size: 12px;
}

:deep(.v-footer) {
  height: 0px;
}
.mainArea {
  height: calc(100vh - 145px);
  overflow-x: hidden;
}
.formcard {
  margin: -12px -19px 0 -15px;
}
// 分頁器樣式
.demo-pagination-block {
  display: flex;
  justify-content: center;
  justify-items: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
:deep(.el-pagination__sizes > .el-select) {
  margin-top: -3px;
}
:deep(.el-pager li) {
  font-size: 12px;
  height: 28px;
  margin-top: -1px;
}
:deep(.el-pagination span:not([class*='suffix'])) {
  font-size: 12px;
}
</style>
